#include "tcp_server.hpp"
#include "protocol.hpp"
#include "Calculate.hpp"
void HandlerRequest(NetWork::Socket *s)
{
    std::string recv_package;
    std::string send_package;
    int recv_size = 1024;
    std::unique_ptr<Protocol::Factory> factory = std::make_unique<Protocol::Factory>();
    std::shared_ptr<Protocol::Request> request = factory->BuildRequest();
    while (1)
    {
        // 1.信息获取
        
        // 服务器获取客户端传来的字节流报文
        if (s->Recv(&recv_package, recv_size) == false)
            break;
        // 分析报文
        std::string message;
        if (Protocol::Decode(recv_package, &message) == false) // 报文不完整
            continue;
        // 进行反序列化
        if (request->Deserialize(message) == false)
            break;
        
        
        // 2.进行处理
        request->Print();
        
        Calculate::Calculate object;
        auto response = object.Cal(request);
        // 序列化返回结果
        if (response->Serialize(&send_package) == false)    // 转为字节流失败
            break;
        
        // 构建报文
        send_package = Protocol::Encode(send_package);
        // 将结果发送给客户端
        if(s->Send(send_package) == false)
            break;
    }
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
    }
    uint16_t port = std::stoi(argv[1]);
    TcpServer ts(port, HandlerRequest);
    ts.Init();
    ts.Start();
}